﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using Landpy.LogAnalyzer.Common;
using Landpy.LogAnalyzer.Core;
using Landpy.LogAnalyzer.Log;

namespace Landpy.LogAnalyzer.Configuration
{
    internal class ConfigurationSession
    {
        private static ConfigurationSession configurationContext;
        private static readonly object lockObject = new object();

        private ConfigurationSession()
        {
            IConfigurationReader configurationReader = new ConfigurationReader(ConfigurationParam.SettingFileName);
            Setting = configurationReader.GetSetting();
        }

        public Setting Setting { get; private set; }

        public static ConfigurationSession GetSession()
        {
            lock (lockObject)
            {
                if (configurationContext == null)
                {
                    lock (lockObject)
                    {
                        configurationContext = new ConfigurationSession();
                    }
                }
                else
                {
                    // N/A.
                }
            }
            return configurationContext;
        }

        public void BuildDefaultSetting()
        {
            var setting = new Setting();
            setting.GlobalFilterStartFlag = "GlobalFilterStartFlag";
            setting.GlobalFilterEndFlag = "GlobalFilterEndFlag";
            var logColumns = new List<LogColumn>();
            var logColumn = new LogColumn();
            logColumn.HeaderText = "ColumnHeaderText";
            logColumn.Filter = "LogColumnFilter";
            logColumns.Add(logColumn);
            var logColumnSchema = new LogColumnSchema();
            logColumnSchema.Columns = logColumns;
            setting.LogColumnShcema = logColumnSchema;
            string serializedString = SerializeProvider.Serialize(setting);
            using (TextWriter textWriter = new StreamWriter(ConfigurationParam.SettingFileName, false, Encoding.Default)
                )
            {
                textWriter.Write(serializedString);
                textWriter.Close();
            }
            Setting = setting;
        }
    }
}